//
//  SunMyOrderVC.m
//  Xspcf
//
//  Created by sunshine on 16/10/27.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "SunMyOrderVC.h"
#import "MJRefresh.h"
#import "SunOrderCell.h"
#import "SunProductDetailVC.h"
#import "SunDelegateWebVC.h"
#import <UMSocialCore/UMSocialCore.h>
#import "SunWebVC.h"
#import "ColorButton.h"
#import "TestViewController.h"

#import "BannerDetailViewController.h"

@interface SunMyOrderVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *_scroll;
    UITableView *_tb;
    UIView *_blank;
    int _selected;
    NSArray *_dataArr;
    NSMutableArray *_arr1;
    NSMutableArray *_arr2;
    NSMutableArray *_arr3;
    int _page1;
    int _page2;
    int _page3;
    UIView *_shareMenu;
    BOOL _isDraw;
}
@end

@implementation SunMyOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND;
    self.title = @"我的投资";
    [self initData];
    [self creatUI];
    [[Sun shareSun]showActivity:self];
    [self request1ToUpdate:YES];
    [self request2ToUpdate:NO];
    [self request3ToUpdate:NO];
//    [self shouldShare];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)shouldShare{
    NSDictionary *user = [Sun getUser:USER];
    if ([[user objectForKey:@"shareTime"] intValue]==1) {
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYYMMdd"];
        NSString *DateTime = [formatter stringFromDate:date];
        NSDictionary *share = [Sun getUser:SHARE];
        if (share) {
            if ([[share objectForKey:@"time"] isEqualToString:DateTime] && [[Sun getUser:ACCESSID] isEqualToString:[share objectForKey:@"accessId"]]) {
                if ([[share objectForKey:@"num"]intValue] < 2) {
                    share = @{@"num":@"2",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
                    [Sun setUser:share forKey:SHARE];
                    [self creatShareMenu];
                }
            }else {
                share = @{@"num":@"1",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
                [Sun setUser:share forKey:SHARE];
                [self creatShareMenu];
            }
        }else {
            share = @{@"num":@"1",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
            [Sun setUser:share forKey:SHARE];
            [self creatShareMenu];
        }
    }else {
        NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_USERINFO];
        [HttpRequest postURL:url withParam:nil success:^(id requestDic, NSString *msg) {
            if ([[requestDic objectForKey:@"shareTime"] intValue]==1) {
                NSDate *date = [NSDate date];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateStyle:NSDateFormatterMediumStyle];
                [formatter setTimeStyle:NSDateFormatterShortStyle];
                [formatter setDateFormat:@"YYYYMMdd"];
                NSString *DateTime = [formatter stringFromDate:date];
                NSDictionary *share = [Sun getUser:SHARE];
                if (share) {
                    if ([[share objectForKey:@"time"] isEqualToString:DateTime] && [[Sun getUser:ACCESSID] isEqualToString:[share objectForKey:@"accessId"]]) {
                        if ([[share objectForKey:@"num"]intValue] < 2) {
                            share = @{@"num":@"2",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
                            [Sun setUser:share forKey:SHARE];
                            [self creatShareMenu];
                        }
                    }else {
                        share = @{@"num":@"1",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
                        [Sun setUser:share forKey:SHARE];
                        [self creatShareMenu];
                    }
                }else {
                    share = @{@"num":@"1",@"time":DateTime,@"accessId":[Sun getUser:ACCESSID]};
                    [Sun setUser:share forKey:SHARE];
                    [self creatShareMenu];
                }
            }
        } failure:^(NSString *errorInfo, int code) {
            [[Sun shareSun]showMsg:errorInfo];
        }];
    }
}

- (void)creatShareMenu{
    [[NSUserDefaults standardUserDefaults] setObject:0 forKey:KactivityApp];
    if (!_shareMenu) {
        _shareMenu = [[UIView alloc]init];
        UIImageView *img = [[UIImageView alloc]init];
        [_shareMenu addSubview:img];
        [img lt_setSize:CGSizeMake(X(350), Y(305)) save:YES];
        [img lt_XcenterTo:nil save:YES];
        [img lt_layoutView:img side:SunCenterY to:nil toSide:SunCenterY withSize:1 offset:-Y(30) save:YES];
        img.image = [UIImage imageNamed:@"third_shareImg"];
        UIButton *cancel = [[UIButton alloc]init];
        [_shareMenu addSubview:cancel];
        [cancel lt_setTop:Y(40) to:img save:YES];
        [cancel lt_XcenterTo:nil save:YES];
        [cancel setImage:[UIImage imageNamed:@"tool_bigcancel"] forState:UIControlStateNormal];
        [cancel addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
        UIButton *btn = [[UIButton alloc]init];
        btn.tag = 1;
        [_shareMenu addSubview:btn];
        [btn lt_XcenterTo:nil save:YES];
        [btn lt_layoutView:btn side:SunTop to:img toSide:SunBottom withSize:1 offset:-Y(30) save:YES];
        [btn addTarget:self action:@selector(btnclick) forControlEvents:UIControlEventTouchUpInside];
    }
    UIButton *btn = [_shareMenu viewWithTag:1];
    if (_isDraw) {
        [btn setImage:[UIImage imageNamed:@"third_shareBtn2"] forState:UIControlStateNormal];
    }else {
        [btn setImage:[UIImage imageNamed:@"third_shareBtn1"] forState:UIControlStateNormal];
    }
    [_shareMenu lt_removeAllCons];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [[Sun shareSun]show:_shareMenu to:window shouldReturn:NO];
    [_shareMenu lt_All:SunEdgesMake(0, 0, 0, 0) save:YES];
}

- (void)btnclick{
    if (_isDraw) {
        [[Sun shareSun]hideShow];
        SunWebVC *vc = [[SunWebVC alloc]init];
        NSString *str = @"CZfSDQzsuDayjfzE";
        NSString *str1 =@"12345678";
        NSString *token_id=[Utility encryptStr:[NSString stringWithFormat:@"%@",[Sun getUser:ACCESSID]]  Key:str1 IV:nil];
        NSString *md5Str=[Utility md5:[NSString stringWithFormat:@"source=ios&token_id=%@&type=5&%@",token_id,str]];
        vc.urlStr = [NSString stringWithFormat:@"%@/draw/wheel?source=ios&token_id=%@&type=5&sign=%@",KWAP,token_id,md5Str];
        [self.navigationController pushViewController:vc animated:YES];
//        TestViewController *test = [[TestViewController alloc]init];
//        test.type = @"5";
//        self.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:test animated:YES];
    }else {
        [self requestToActivity];
    }
}

-(void)requestToActivity{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_TENDERSHARE];
    [HttpRequest postURL:url withParam:nil success:^(id requestDic, NSString *msg) {
        NSString *img = [requestDic objectForKey:@"img"];
        if (![img containsString:@"http"]) {
            img = [KIMG stringByAppendingString:img];
        }
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[requestDic objectForKey:@"title"] descr:[requestDic objectForKey:@"content"] thumImage:img];
        shareObject.webpageUrl =[requestDic objectForKey:@"url"];
        messageObject.shareObject = shareObject;
        [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            if (error) {
            }else{
                [self shareSuccess];
            }
        }];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]showMsg:errorInfo];
    }];
    
}

- (void)shareSuccess{
    _isDraw = YES;
    [self creatShareMenu];
    [self sharedSuccessForRequest];
}

-(void)sharedSuccessForRequest{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_SHARESUCC];
    [HttpRequest postURL:url withParam:@{@"actType":[[Sun getUser:DRAWTYPE] objectForKey:@"prizetender"]} success:^(id requestDic, NSString *msg) {
        NSMutableDictionary *user = [NSMutableDictionary dictionaryWithDictionary:[Sun getUser:USER]];
        [user setObject:@"0" forKey:@"shareTime"];
        [Sun setUser:user forKey:USER];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

- (void)hide{
    [[Sun shareSun]hideShow];
}

- (void)initData{
    _arr1 = [NSMutableArray array];
    _arr2 = [NSMutableArray array];
    _arr3 = [NSMutableArray array];
    _page1 = 1;
    _page2 = 1;
    _page3 = 1;
}

- (BOOL)navigationShouldPopOnBackButton {
    [self.navigationController popToRootViewControllerAnimated:YES];
    return NO;
}

- (void)creatUI{
    UIButton *btn1 = [[UIButton alloc]init];
    [self.view addSubview:btn1];
    btn1.tag = 1;
    [btn1 lt_Top:SunEdgesMake(0, 0, SCREENWIDTH / 3 * 2, Y(46)) to:nil save:YES];
    btn1.backgroundColor = WHITE;
    [btn1 setTitle:@"招标中" forState:UIControlStateNormal];
    [btn1 setTitleColor:BLACK forState:UIControlStateNormal];
    [btn1 setTitleColor:BLUE forState:UIControlStateSelected];
    btn1.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn1 addTarget:self action:@selector(btnSelect:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *btn2 = [Sun copyWithView:btn1];
    [self.view addSubview:btn2];
    btn2.tag = 2;
    [btn2 lt_Top:SunEdgesMake(0, SCREENWIDTH / 3, SCREENWIDTH / 3, Y(46)) to:nil save:YES];
    [btn2 setTitle:@"还款中" forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(btnSelect:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *btn3 = [Sun copyWithView:btn1];
    [self.view addSubview:btn3];
    btn3.tag = 3;
    [btn3 lt_Top:SunEdgesMake(0, SCREENWIDTH / 3 * 2, 0, Y(46)) to:nil save:YES];
    [btn3 setTitle:@"已还款" forState:UIControlStateNormal];
    [btn3 addTarget:self action:@selector(btnSelect:) forControlEvents:UIControlEventTouchUpInside];
    _scroll = [[UIView alloc]init];
    [self.view addSubview:_scroll];
    CGSize size =[@"招标中" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    [_scroll lt_setSize:CGSizeMake(size.width, Y(2)) save:YES];
    [_scroll lt_bottomEqual:btn1 save:YES];
    [_scroll lt_XcenterTo:btn1 save:YES];
    _scroll.backgroundColor = BLUE;
    UILabel *point1 = [[UILabel alloc]init];
    [self.view addSubview:point1];
    [point1 lt_setSize:CGSizeMake(X(18), X(18)) save:YES];
    [point1 lt_layoutView:point1 side:SunBottom to:btn1 toSide:SunCenterY withSize:1 offset:0 save:YES];
    [point1 lt_layoutView:point1 side:SunLeft to:btn1 toSide:SunCenterX withSize:1 offset:size.width / 2 save:YES];
    point1.tag = 4;
    point1.layer.cornerRadius = X(9);
    point1.clipsToBounds = YES;
    point1.backgroundColor = RED;
    point1.textAlignment = NSTextAlignmentCenter;
    point1.textColor = WHITE;
    point1.font = [UIFont systemFontOfSize:10];
    point1.hidden = YES;
    UILabel *point2 = [Sun copyWithView:point1];
    [self.view addSubview:point2];
    [point2 lt_setSize:CGSizeMake(X(18), X(18)) save:YES];
    [point2 lt_layoutView:point2 side:SunBottom to:btn2 toSide:SunCenterY withSize:1 offset:0 save:YES];
    [point2 lt_layoutView:point2 side:SunLeft to:btn2 toSide:SunCenterX withSize:1 offset:size.width / 2 save:YES];
    point2.tag = 5;
    point2.layer.cornerRadius = X(9);
    point2.clipsToBounds = YES;
    point2.hidden = YES;
    _selected = 1;
    btn1.selected = YES;
    btn1.userInteractionEnabled = NO;
    _tb = [[UITableView alloc]initWithFrame:CGRectNull style:UITableViewStyleGrouped];
    [self.view addSubview:_tb];
    [_tb lt_All:SunEdgesMake(Y(46), 0, 0, 0) save:YES];
    _tb.delegate = self;
    _tb.dataSource = self;
    _tb.backgroundColor = BACKGROUND;
    _tb.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tb.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    _tb.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    for (int i = 1; i <= 5; i ++) {
        UIView *view = [self.view viewWithTag:i];
        [self.view bringSubviewToFront:view];
        [self.view bringSubviewToFront:_scroll];
    }
}

- (void)creatBlank{
    _blank = [[UIView alloc]init];
    [self.view addSubview:_blank];
    [_blank lt_All:SunEdgesMake(Y(46), 0, 0, 0) save:YES];
    _blank.backgroundColor = BACKGROUND;
    UIImageView *img = [[UIImageView alloc]init];
    [_blank addSubview:img];
    [img lt_XcenterTo:nil save:YES];
    img.image = [UIImage imageNamed:@"third_order_blank"];
    UILabel *label = [[UILabel alloc]init];
    [_blank addSubview:label];
    [label lt_XcenterTo:nil save:YES];
    [label lt_setTop:Y(18) to:img save:YES];
    [label lt_layoutView:label side:SunCenterY to:nil toSide:SunCenterY withSize:1 offset:Y(20) save:YES];
    label.textColor = GRAY;
    label.font = [UIFont systemFontOfSize:19];
    label.text = @"暂无相关记录！";
}

- (void)refresh{
    if (_selected == 1) {
        [_arr1 removeAllObjects];
        _page1 = 1;
    }else if (_selected == 2){
        [_arr2 removeAllObjects];
        _page2 = 1;
    }else{
        [_arr3 removeAllObjects];
        _page3 = 1;
    }
    [self loadMore];
}

- (void)loadMore{
    if (_selected == 1) {
        [self request1ToUpdate:YES];
    }else if (_selected == 2){
        [self request2ToUpdate:YES];
    }else{
        [self request3ToUpdate:YES];
    }
}

- (void)update{
    if (_selected == 1) {
        _dataArr = _arr1;
    }else if (_selected == 2) {
        _dataArr = _arr2;
    }else if (_selected == 3) {
        _dataArr = _arr3;
    }
    if (_dataArr.count == 0) {
        if (!_blank) {
            [self creatBlank];
        }
        _blank.hidden = NO;
    }else {
        if (_blank) {
            _blank.hidden = YES;
        }
        [_tb reloadData];
    }
    for (int i = 1; i <= 5; i ++) {
        UIView *view = [self.view viewWithTag:i];
        [self.view bringSubviewToFront:view];
        [self.view bringSubviewToFront:_scroll];
    }
}

- (void)btnSelect:(UIButton *)sender{
    if (sender.tag == _selected) {
        return;
    }
    _selected = (int)sender.tag;
    for (int i=1; i<=3; i++) {
        UIButton *btn = [self.view viewWithTag:i];
        if (i == _selected) {
            btn.userInteractionEnabled = NO;
            btn.selected = YES;
            CGSize size =[@"招标中" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
            [_scroll lt_removeAllCons];
            [UIView animateWithDuration:0.2 animations:^{
                [_scroll lt_setSize:CGSizeMake(size.width, Y(2)) save:YES];
                [_scroll lt_bottomEqual:btn save:YES];
                [_scroll lt_XcenterTo:btn save:YES];
                [self.view layoutIfNeeded];
            }];
        }else {
            btn.userInteractionEnabled = YES;
            btn.selected = NO;
        }
    }
    [self update];
}

- (void)request1ToUpdate:(BOOL)update{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_RECORD_BORROWING];
    [HttpRequest postURL:url withParam:@{@"page":[NSString stringWithFormat:@"%d",_page1]} success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideActivity];
        _page1 ++;
        [_arr1 addObjectsFromArray:[requestDic objectForKey:@"list"]];
        UILabel *point = [self.view viewWithTag:4];
        if ([[requestDic objectForKey:@"totalNum"] intValue] > 0) {
            point.hidden = NO;
            point.text = [NSString stringWithFormat:@"%d",[[requestDic objectForKey:@"totalNum"] intValue]];
        }else {
            point.hidden = YES;
        }
        [_tb.mj_header endRefreshing];
        [_tb.mj_footer endRefreshing];
        NSArray *dataArray = [requestDic objectForKey:@"list"];
        if (dataArray.count <= 0){
            [_tb.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_tb.mj_footer resetNoMoreData];
        }
        
        if (update) {
            [self update];
        }
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

-(void)request2ToUpdate:(BOOL)update{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_RECORD_REPAYING];
    [HttpRequest postURL:url withParam:@{@"page":[NSString stringWithFormat:@"%d",_page2]} success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideActivity];
        _page2 ++;
        [_arr2 addObjectsFromArray:[requestDic objectForKey:@"list"]];
        UILabel *point = [self.view viewWithTag:5];
        if ([[requestDic objectForKey:@"totalNum"] intValue] > 0) {
            point.hidden = NO;
            point.text = [NSString stringWithFormat:@"%d",[[requestDic objectForKey:@"totalNum"] intValue]];
        }else {
            point.hidden = YES;
        }
        [_tb.mj_header endRefreshing];
        [_tb.mj_footer endRefreshing];
        NSArray *dataArray = [requestDic objectForKey:@"list"];
        if (dataArray.count <= 0){
            [_tb.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_tb.mj_footer resetNoMoreData];
        }
        
        if (update) {
            [self update];
        }
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

-(void)request3ToUpdate:(BOOL)update{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_RECORD_REPAYED];
    [HttpRequest postURL:url withParam:@{@"page":[NSString stringWithFormat:@"%d",_page3]} success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideActivity];
        _page3 ++;
        [_arr3 addObjectsFromArray:[requestDic objectForKey:@"list"]];
        [_tb.mj_header endRefreshing];
        [_tb.mj_footer endRefreshing];
        NSArray *dataArray = [requestDic objectForKey:@"list"];
        if (dataArray.count <= 0){
            [_tb.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_tb.mj_footer resetNoMoreData];
        }
        
        if (update) {
            [self update];
        }
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

#pragma mark tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return Y(155);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SunOrderCell *cell = [SunOrderCell cellWithTableView:tableView];
    [cell setCellData:_dataArr[indexPath.row] selected:_selected];
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = BACKGROUND;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return Y(15);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *data = _dataArr[indexPath.row];
    SunProductDetailVC *vc = [[SunProductDetailVC alloc]init];
    vc.borrowId = [data objectForKey:@"borrowId"];
    vc.title = [data objectForKey:@"name"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
